// Simple React-like implementation

// Virtual DOM node
class VNode {
    constructor(type, props, children) {
        this.type = type;
        this.props = props;
        this.children = children;
    }
}

// Component base class
class Component {
    constructor(props) {
        this.props = props;
        this.state = {};
    }

    setState(partialState) {
        this.state = { ...this.state, ...partialState };
        ReactDOM.rerender();
    }

    render() {
        return null;
    }
}

// React-like API
const React = {
    createElement(type, props, ...children) {
        return new VNode(type, props || {}, children);
    },

    Component
};

// ReactDOM-like API
const ReactDOM = {
    vdom: null,
    rootContainer: null,

    render(vnode, container) {
        this.vdom = vnode;
        this.rootContainer = container;
        const realDOM = this.createDOM(vnode);
        container.appendChild(realDOM);
    },

    rerender() {
        const container = this.rootContainer;
        container.innerHTML = '';
        const realDOM = this.createDOM(this.vdom);
        container.appendChild(realDOM);
    },

    createDOM(vnode) {
        if (typeof vnode === 'string' || typeof vnode === 'number') {
            return document.createTextNode(vnode);
        }

        if (typeof vnode.type === 'function') {
            const component = new vnode.type(vnode.props);
            const renderedVNode = component.render();
            return this.createDOM(renderedVNode);
        }

        const element = document.createElement(vnode.type);

        // Set props
        Object.entries(vnode.props).forEach(([name, value]) => {
            if (name.startsWith('on')) {
                element.addEventListener(name.toLowerCase().slice(2), value);
            } else {
                element.setAttribute(name, value);
            }
        });

        // Append children
        vnode.children.forEach(child => {
            const childDOM = this.createDOM(child);
            element.appendChild(childDOM);
        });

        return element;
    }
};

// Export
export { React, ReactDOM };